<template>
	<el-main class="bg table_wrap exams">
		<!-- table头部检索 -->
		<div class="div-form">
			<el-form ref="elFormRef" :model="formInline" label-width="90px" :style="{ width: '100%' }" label-position="left">
				<el-row class="rows row1">
					<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
						<el-form-item label="科目名称">
							<el-select v-model="formInline.subject_name">
								<el-option v-for="obj in list_subject" :key="obj.name" :label="obj.name" :value="obj.name">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="5">
						<el-form-item label="名称">
							<el-input v-model="formInline.name"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<baseTable :tableColumns="columns" :tableFuntWidth='320' :requestApi="url_get_list" :isShowSelect="true"
			:imgflag="false" :vm="vm" v-model:isRefresh="isRefresh" :otherParams="formInline" :isExportTableDataList="true"
			@handleTableDataList="handleTableDataList" @handleSelectionChange="handleSelectionChange"
			@handleCurrentChangeNew="handleCurrentChangeNew">
			<!-- 头部按钮 -->
			<template #baseHeadFunt>
				<el-button type="primary" @click="onSubmit">查询</el-button>
				<el-button @click="onReset(true)">重置</el-button>
				<el-button type="danger" v-if="
			  user_group == '管理员' || $check_action('/subject_exam/table', 'del')
			" class="search_btn_del" @click="delInfo()">删除</el-button>
				<!-- <el-button v-if="user_group == '管理员' || $check_action('/subject_exam/table', 'add')"
					class="float-right search_btn_add" @click="router.push('./exams_view?')">添加</el-button> -->
			</template>
			<!-- table内操作 -->
			<template #baseTableFunt="{ scope }">
				<el-button v-if="user_group == '管理员' || $check_action('/subject_exam/table', 'set')" type="primary" size="small"
					@click="router.push('./exams_view?' + field + '=' + scope.row.exam_id)">详情</el-button>
				<el-button v-if="
              user_group == '管理员' || $check_action('/exam_question_database/table', 'get') || $check_action('/exam_question_database/table', 'set')
            " type="primary" size="small"
					@click="router.push('./question_table?' + field + '=' + scope.row.exam_id)">题库</el-button>
				<el-button class="e-button"
					:data-num='getObj2(scope.row[field]).score_state || getObj2(scope.row[field]).exam_id'
					v-if="(user_group == '管理员' || $check_exam('/exam/table', 'answers')) && (getObj2(scope.row[field]).score_state || getObj2(scope.row[field]).exam_id)"
					@click="router.push('./answer_view?' + field + '=' + scope.row[field])" size="small">
					<span>查看分数</span>
				</el-button>
				<el-button class="e-button" v-else-if="
					$check_option('/subject_exam/table', 'answers') &&
					scope.row.status === '启用'
				" @click="router.push('./answer_view?' + field + '=' + scope.row.exam_id)" size="small">
					<span>答题</span>
				</el-button>
				<el-button class="e-button el-button--small is-plain el-button--primary"
					v-if="user_group == '管理员' || $check_exam('/subject_exam/table', 'give_score')"
					@click="router.push('./score_table?' + field + '=' + scope.row.exam_id)" size="small">
					<span>评分</span>
				</el-button>
				<!-- <el-button
		  v-if="user_group == '管理员' || $check_action('/subject_exam/table', 'get')"
			type="primary"
			size="small"
			@click="router.push('./exams_view?' + field + '=' + scope.row.exam_id)"
			>详情</el-button
		  > -->
				<!-- <el-button
		  v-if="
              user_group == '管理员' || $check_action('/exam_question_database/table', 'get') || $check_action('/exam_question_database/table', 'set')
            "
			type="primary"
			size="small"
			@click="router.push('./question_table?' + field + '=' + scope.row.exam_id)"
			>题库</el-button
		  >
		  <el-button  class="e-button"  :data-num='getObj2(scope.row[field]).score_state||getObj2(scope.row[field]).exam_id'  v-if="(user_group == '管理员' || $check_exam('/exam/table','answers')) && getObj2(scope.row[field]).score_state||getObj2(scope.row[field]).exam_id"
		  @click="router.push('./answer_view?' + field + '=' + scope.row[field])" size="small">
				<span>查看分数</span>
			</el-button>
			<el-button class="e-button"   v-else-if="
                $check_option('/subject_exam/table', 'answers') &&
                scope.row.status === '启用'
              "
			@click="router.push('./answer_view?' + field + '=' + scope.row[field])" size="small">
				<span>答题</span>
			</el-button> -->
				<el-button class="e-button" v-if="(user_group == '管理员' ||$check_option('/subject_exam/table','subject_exam')) "
					@click="router.push('./genQuestion?' + field + '=' + scope.row[field]+'&subject_name=' +
              scope.row['subject_name'])" size="small">
					<span>生成</span>
				</el-button>

				<!-- <el-button class="e-button" v-if="user_group == '管理员' || $check_option('/subject_exam/table','give_score')"
			@click="router.push('./score_table?' + field + '=' + scope.row[field])" size="small">
				<span>评分</span>
			</el-button> -->
			</template>
			<template #baseTableFunt2="{ scope }">
				<el-button v-if="user_group == '管理员' || $check_action('/subject_exam/table', 'get')" type="primary" size="small"
					@click="router.push('./exams_view?' + field + '=' + scope.exam_id)">详情</el-button>
				<el-button v-if="
              user_group == '管理员' || $check_action('/exam_question_database/table', 'get') || $check_action('/exam_question_database/table', 'set')
            " type="primary" size="small"
					@click="router.push('./question_table?' + field + '=' + scope.exam_id)">题库</el-button>
				<el-button class="e-button" :data-num='getObj2(scope[field]).score_state||getObj2(scope[field].exam_id)'
					v-if="(user_group == '管理员' || $check_exam('/exam/table','answers')) && getObj2(scope[field]).score_state||getObj2(scope[field].exam_id)"
					@click="router.push('./answer_view?' + field + '=' + scope[field])" size="small">
					<span>查看分数{{scope[field]}}</span>
				</el-button>
				<el-button class="e-button" v-else-if="
                $check_option('/subject_exam/table', 'answers') &&
                scope.status === '启用'
              " @click="router.push('./answer_view?' + field + '=' + scope[field])" size="small">
					<span>答题{{scope[field]}}</span>
				</el-button>
				<el-button class="e-button" v-if="(user_group == '管理员' ||$check_option('/subject_exam/table','subject_exam')) "
					@click="router.push('./genQuestion?' + field + '=' + scope[field]+'&subject_name=' +
              scope['subject_name'])" size="small">
					<span>生成</span>
				</el-button>

				<el-button class="e-button" v-if="user_group == '管理员' || $check_option('/subject_exam/table','give_score')"
					@click="router.push('./score_table?' + field + '=' + scope[field])" size="small">
					<span>评分</span>
				</el-button>
			</template>
			<!-- 特殊表格内容 -->
			<template #tableContent="{ scope, column }">
				<span v-if="column.prop === 'create_time'">{{
					formatDate(scope.row.create_time)
					}}</span>
				<span v-if="column.prop === 'user_id'">{{getObj(user_list,scope.row.user_id,'user_id').username}}</span>
				<span v-if="column.prop === 'update_time'">{{
					formatDate(scope.row.update_time)
					}}</span>
			</template>
			<template #tableContent2="{ scope, column }">
				<span v-if="column.prop === 'create_time'">{{ column.label }}：{{
					formatDate(scope.create_time)
					}}</span>
				<span v-if="column.prop === 'update_time'">{{ column.label }}：{{
					formatDate(scope.update_time)
					}}</span>
			</template>
		</baseTable>
	</el-main>
</template>
  <script setup>
  import { useRouter } from "vue-router";
  let router = useRouter();
  import {
	$check_option,
	$check_exam,
	$fullUrl,
	formatDate,
	$banseUrl,
	$check_action,
  } from "@/utils/utils.js";
  import { $post, $get } from "@/api/Api.js";
  import { Picture } from "@element-plus/icons-vue";
  import { ElMessage } from "element-plus";
  import { ref, toRefs, computed, onMounted } from "vue";
  import storageHelper from "@/libs/StorageHelper";
  let table = ref("subject_exam");
  let field = ref("exam_id");
  let url_get_list = ref("/api/subject_exam/get_list");
  let url_del = ref("/api/subject_exam/del?");
  let user_group = storageHelper.getUserInfo().user_group;
  let user_id = storageHelper.getUserInfo().user_id;
  let answered_list = ref([]);
  //科目
  let list_subject = ref([]);
  let vm=ref({
	id: "exam_id",
    })
  // 列名
  const columns = [
	{ prop: "subject_name", label: "科目名称" },
	{ prop: "name", label: "名称" },
	{ prop: "user_id", label: "出题人" },
	{ prop: "duration", label: "答题时长" },
	{ prop: "score", label: "总分" },
	{ prop: "status", label: "状态" },
	{ prop: "create_time", label: "创建时间" },
	{ prop: "update_time", label: "更新时间" },
  ];
  // 刷新table
  let isRefresh = ref(false);
  
  //批量勾选数据
  let selectList = ref([]);

  //点击当前行数据
  let currentRowTableProduct = ref({});
  //表格勾选回调
  let handleSelectionChange = (val) => {
	selectList.value = val.map((item) => {
	  return item.exam_id;
	});
  };
  //点击当前行
  let handleCurrentChangeNew = (val) => {
	currentRowTableProduct.value = val;
  };
  // 批量删除
  let delInfo = () => {
	ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
	  confirmButtonText: "确定",
	  cancelButtonText: "取消",
	  type: "warning",
	})
	  .then(() => {
		selectList.value.map((item) => {
		  delFun(item);
		});
	  })
	  .catch(() => {
		ElMessage({
		  type: "info",
		  message: "取消操作",
		});
	  });
  };
  
  // 调用删除方法
  let delFun = (id) => {
	$get(url_del.value + "exam_id=" + id).then((json) => {
	  if (json.result) {
		ElMessage.success("删除成功");
	  } else if (json.error) {
		ElMessage.error(json.error);
	  }
	  isRefresh.value = true;
	});
  };
  
  let table_class = ({ row, column, rowIndex, columnIndex }) => {
	return "table_class";
  };
  // 头部搜索// 搜索
  let formInline = ref({
	name: "",
	orderby:'create_time desc',
  });
  // 搜索
  let onSubmit = () => {
	isRefresh.value = true;
  };
  
  // 重置
  let onReset = (refresh) => {
	formInline.value = {
	  name: "",
	  orderby:'create_time desc',
	};
	isRefresh.value = refresh;
  };
  // table暴露出来的数据
  let list=ref([])
  let handleTableDataList = (data) => {
	answered_list.value=[]
	list.value = data;
	get_list_after()
	// isRefresh.value = true;
  };
  let get_answered_list=(val)=>{
	let obj = answered_list.value.some(item => item.exam_id === val)
	console.log(obj)
	if(obj){
		return true;

	}else{
		return false;
	}
	  
  }
  let get_list_after=()=>{
		for (let i=0;i<list.value .length;i++){
			get_user_answer_state(list.value[i].exam_id);
		}
	}
  let get_user_answer_state = (exam_id) => {
	$get("/api/subject_user_answer/get_obj?user_id="+user_id+"&exam_id="+exam_id).then((res) => {
		if(res.result && res.result.obj != null){
				answered_list.value.push(res.result.obj)
				
				//_this.$set(_this.answered_list,exam_id,true)
			}else {
				// answered_list.value.push(res.result.obj)
				//_this.$set(_this.answered_list,exam_id,false)
			}
      });
  };

let user_list=ref([])
  let get_user_by_id=()=> {
      $get("/api/user/get_list").then((res) => {
        if (res.result && res.result.list) {
          user_list.value = res.result.list;
        }
      });
    }
// 查询数组对象某个是否包含某个值,返回对应对象
// 查询数组对象某个是否包含某个值,返回对应对象
let getObj = (arr, val) => {
  let obj = arr.find((item) => item.user_id == val);
  if (obj) {
    return obj;
  } else {
    return "-";
  }
};
let getObj2 = (val) => {
  let obj = answered_list.value.find((item) => item.exam_id == val);
  if (obj) {
    return obj;
  } else {
    return "-";
  }
};
   // 获取科目列表
   let get_subject_list = async () => {
      let json = await $get("/api/subject/get_list");
      if (json.result) {
      list_subject.value = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
   }
  onMounted(() => {
	get_user_by_id()
	if (user_group!=='管理员' && $check_option("/subject_exam/table","teacher")){
       url_get_list.value =url_get_list.value + "&user_id="+user_id
      }
    get_subject_list()
  

  });
  </script>
  <style lang="less" scoped>
  .div-form {
	padding: 10px;
  }
  </style>